﻿/*
 * @autor: hector
 * @fecha: 20/07/2012
 * @project: Pascal's Triangle
 * 
 */
using System;

namespace PascalTriangle
{
    class Program
    {
        static void Main(string[] args)
        {
            GetPascalTriangleRecursive(4);
            Console.WriteLine();
            Console.WriteLine();
            int[,] pascal = GetPascalTriangleIterative(4);

            for (int i = 0; i < pascal.GetLength(0); i++)
            {
                for (int j = 0; j < pascal.GetLength(1); j++)
                {
                    Console.Write(" {0} ", pascal[i, j] != 0 ? pascal[i, j].ToString() : string.Empty);
                }
                Console.WriteLine();
            }

            Console.ReadLine();
        }

        public static int[,] GetPascalTriangleIterative(int level)
        {
            if (level <= 2)
                throw new InvalidOperationException("The level must be greater than 2");

            int x = level;
            int y = level * 2 - 1;

            int begin = 0;
            int end = 0;

            int[,] pascal = new int[x, y];

            int i = 0;

            do
            {
                begin = (pascal.GetLength(1) - 1) / 2 - i;
                end = (pascal.GetLength(1) - 1) / 2 + i;

                pascal[i, begin] = 1;
                pascal[i, end] = 1;
                begin += 2;

                while (begin < end)
                {
                    pascal[i, begin] = pascal[i - 1, begin - 1] + pascal[i - 1, begin + 1];
                    begin += 2;
                }

                i++;

            } while (i < level);


            return pascal;

        }

        public static int[] GetPascalTriangleRecursive(int level)
        {
            if (level == 1)
            {
                Console.WriteLine(1);
                return new int[] { 1 };
            }

            int[] previous = GetPascalTriangleRecursive(level - 1);

            int[] current = GetCurrent(previous);

            Display(current);

            return current;
        }

        private static int[] GetCurrent(int[] previous)
        {
            int[] current = new int[previous.Length + 1];

            current[0] = 1;
            current[current.Length - 1] = 1;

            for (int i = 1; i < current.Length - 1; i++)
                current[i] = previous[i - 1] + previous[i];

            return current;
        }

        private static void Display(int[] current)
        {
            for (int i = 0; i < current.Length; i++)
                Console.Write("{0} ", current[i]);

            Console.WriteLine();
        }
    }
}